//
//  CZEmotionInputView.swift
//  表情键盘
//
//  Created by Albert Zhu on 16/10/27.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit

private let cellId = "cellId"

class CZEmotionInputView: UIView {
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var toolbar: CZEmotionToolbar!
    @IBOutlet weak var pageControl: UIPageControl! {
        didSet {
            let bundle = CZEmotionManager.shared.bundle
            guard let normalImage = UIImage(named: "other/compose_keyboard_dot_normal", in: bundle, compatibleWith: nil),
                let selectedImage = UIImage(named: "other/compose_keyboard_dot_selected", in: bundle, compatibleWith: nil) else {return}
            
            // 利用运行时设置自定义图片
            pageControl.setValue(normalImage, forKey: "_pageImage")
            pageControl.setValue(selectedImage, forKey: "_currentPageImage")
        }
    }
    
    var selectedEmotionBlock: ((CZEmotionModel?)->())?
    
    class func inputView(completion: @escaping (CZEmotionModel?)->()) -> CZEmotionInputView {
        let nib = UINib(nibName: "CZEmotionInputView", bundle: nil)
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as! CZEmotionInputView
        
        view.selectedEmotionBlock = completion
        
        return view
    }
    
    override func awakeFromNib() {
        
        toolbar.delegate = self
        
        collectionView.register(CZEmotionCell.self, forCellWithReuseIdentifier: cellId)
    }
}

// MARK: - CZEmotionToolbarDelegate
extension CZEmotionInputView: CZEmotionToolbarDelegate {
    func emotionToolbar(_ toolbar: CZEmotionToolbar, didSelected itemIndex: Int) {
        debugPrint(itemIndex)
        
        let indexPath = IndexPath(item: 0, section: itemIndex)
        
        collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
        pageControl.numberOfPages = collectionView.numberOfItems(inSection: indexPath.section)
        pageControl.currentPage = 0
    }
}

extension CZEmotionInputView: UICollectionViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        var center = scrollView.center
        center.x += scrollView.contentOffset.x
        
        let paths = collectionView.indexPathsForVisibleItems
        
        var targetIndexPath: IndexPath?
        
        for indexPath in paths {
            let cell = collectionView.cellForItem(at: indexPath)
            
            if cell?.frame.contains(center) == true {
                
                targetIndexPath = indexPath
                
                break
            }
        }
        guard let target = targetIndexPath else {return}
        
        pageControl.numberOfPages = collectionView.numberOfItems(inSection: target.section)
        pageControl.currentPage = target.item
        toolbar.selectIndex = target.section
    }
}

extension CZEmotionInputView: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return CZEmotionManager.shared.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CZEmotionManager.shared.packages[section].emotions.count / 21 + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CZEmotionCell
        
        cell.emotions = CZEmotionManager.shared.packages[indexPath.section].emotion(page: indexPath.row)
        
        cell.delegate = self
        
        return cell
    }
}

// MARK: - CZEmotionCellDelegate
extension CZEmotionInputView: CZEmotionCellDelegate {
    func emotionCell(_ cell: CZEmotionCell, didSelectedEmotion emotionModel: CZEmotionModel?) {
        debugPrint(cell, emotionModel)
        
        selectedEmotionBlock?(emotionModel)
        
        guard let em = emotionModel else {return}
        
        let indexPath = collectionView.indexPathsForVisibleItems[0]
        if indexPath.section == 0 {
            return
        }
        
        CZEmotionManager.shared.recentEmotion(em: em)
        var indexSet = IndexSet()
        indexSet.insert(0)
        
        collectionView.reloadSections(indexSet)
    }
}
